package com.cyt.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.model.vo.SelectVo;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.dao.SysDictContentDao;
import com.cyt.sys.dao.SysDictDao;
import com.cyt.sys.model.po.SysDict;
import com.cyt.sys.model.po.SysDictContent;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.model.vo.SysDictContentVo;
import com.cyt.sys.model.vo.SysDictViewVo;
import com.cyt.sys.model.vo.SysDictVo;
import com.cyt.sys.service.SysDictContentService;
import com.cyt.sys.service.SysDictService;
import com.cyt.sys.util.cache.CacheUtils;
import com.cyt.sys.util.cache.DictUtils;
import com.cyt.wx.model.po.WxEducationUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 基础部分-数据字典service实现类
 *
 * @author shengQiang yu
 * @date 2019-04-03 10:29
 */
@Service("baseDictService")
public class SysDictServiceImpl extends BaseServiceImpl<SysDict> implements SysDictService {
    @Resource
    private SysDictDao sysDictDao;
    @Resource
    private SysDictContentDao sysDictContentDao;

    private SysDict sysDict;

    @Resource
    private SysDictContentService sysDictContentService;

    @Resource
    private SysDictService sysDictService;

    @Autowired
    public void setBaseDao(SysDictDao sysDictDao) {
        this.baseDao = sysDictDao;
    }
    
    /**
     * 分页查询
     *
     * @param sysDictVo 对象
     * @param pageSize 当前页面
     * @param pageNum 页面数量
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    public ReturnResult page(SysDictVo sysDictVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<SysDict> list= sysDictDao.selectByExample(listExample(sysDictVo));
        PageInfo<SysDict> page=new PageInfo<SysDict>(list);
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 添加或修改
     *
     * @param sysDictVo 对象
     * @param currentUser 当前用户
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(SysDictVo sysDictVo, SysUser currentUser) {
        //是否增加操作
        boolean isAdd=false;
        if (StrUtil.isEmpty(sysDictVo.getId())) {
            isAdd=true;
            sysDict = new SysDict(currentUser);
        } else {
            sysDict = sysDictDao.selectByPrimaryKey(sysDictVo.getId());
            sysDict.setUpdateTime(new Date());
            sysDict.setUpdateUser(currentUser.getId());
        }
        sysDict.setDictGrade(DictCode.DICT_GRADE_YWJB);
        sysDict.setName(sysDictVo.getName());
        sysDict.setCode(sysDictVo.getCode());
        sysDict.setDictKind(sysDictVo.getDictKind());
        sysDict.setUrl(sysDictVo.getUrl());
        sysDict.setStatus(sysDictVo.getStatus());
        sysDict.setRemark(sysDictVo.getRemark());
        if(isAdd){
            //增加操作
            int num = sysDictDao.insert(sysDict);
            if (num <= 0) {
                return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
            }
        }else{
            //修改操作
            int num = sysDictDao.updateByPrimaryKey(sysDict);
            if (num <= 0) {
                return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_UPDATE_FAIL_MSG);
            }
        }
        CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_MSG);
    }


    /**
     * 左边分页查询
     *
     * @param sysDictVo 对象
     * @param pageSize 当前页面
     * @param pageNum 页面数量
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    public ReturnResult pageLeft(SysDictVo sysDictVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" create_time desc");
        List<SysDictVo> list = sysDictContentDao.listLeft(sysDictVo);
        PageInfo<SysDictVo> page=new PageInfo<SysDictVo>(list);
        Map<String,Object> map=new HashedMap();
        map.put("page",page.getList());
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 根据主键id集合软删除
     *
     * @param ids 主键id集合，多个以‘，’隔开
     * @param currentUser 当前用户
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult removeByIds(String ids,SysUser currentUser) {
        String[] idList=ids.split(",");
        boolean flage=true;
        StringBuffer stringBuffer=new StringBuffer();
        for (String id:idList){
            SysDict sysDict = sysDictDao.selectByPrimaryKey(id);
            sysDict.setRemoveTag(BaseConstant.REMOVE_TAG_YES);
            sysDict.setUpdateTime(new Date());
            sysDict.setUpdateUser(currentUser.getId());
            int num= sysDictDao.updateByPrimaryKey(sysDict);
            if(num>0){
                flage=true;
            }else{
                stringBuffer.append("");
            }
            sysDictContentDao.updateByDictType(sysDict.getCode());
        }
        if(flage){
            CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
            return new ReturnResult();
        }else{
            CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_DELETE_FAIL_MSG);
        }
    }
    public List<SysDictViewVo> findBaseDictViewVoList(SysDict sysDict){
      return   sysDictDao.findBaseDictViewVoList();
    }

    /**
     * @Author: YuShengQiang
     * @Date: 2018-12-05 15:54
     * @Description:查询对象集合
     */
    public List<SysDict> listExample(SysDictVo sysDictVo) {
        Example example = new Example(SysDict.class);
        example.setOrderByClause(" update_time desc");
        Example.Criteria criteria = example.createCriteria();
        if(StrUtil.isNotEmpty(sysDictVo.getName())){
            criteria.andLike("name","%"+ sysDictVo.getName()+"%");
        }
        if(StrUtil.isNotEmpty(sysDictVo.getCode())){
            criteria.andLike("code","%"+ sysDictVo.getCode()+"%");
        }
        if(StrUtil.isNotEmpty(sysDictVo.getStatus())){
            criteria.andEqualTo("status", sysDictVo.getStatus());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        return sysDictDao.selectByExample(example);
    }

    /**
     * 根据code码查询字典详情
     *
     * @param  code
     * @return SysDict
     * @author changZheng hou
     * @date 2019/5/9 16:53
     */
    public SysDict listByCode(String code){
        return sysDictDao.listByCode(code);
    }

    /**
     * 获取所有的科目 科目选择器
     *
     * @param sysDictVo 接收参数的对象
     * @return ReturnResult
     * @author Jun Han
     * @date 2019/12/2 14:28
     */
    public ReturnResult selector(SysDictVo sysDictVo){
        //List<SysDict> list = listExample(sysDictVo);
        SysDictContentVo sysDictContentVo = new SysDictContentVo();
        sysDictContentVo.setDictType(sysDictVo.getCode());
        ReturnResult result =  sysDictContentService.list(sysDictContentVo);
        List<SysDictContent> list = (List<SysDictContent>) result.getData();
        List<SelectVo> selectVoList=new ArrayList<>();
        if(list!=null&&list.size()>0){
            for(SysDictContent sysDict :list){
                List<String> showNameList=new ArrayList<>();
                showNameList.add(sysDict.getName());
                showNameList.add(sysDict.getValue());
                selectVoList.add(new SelectVo(sysDict.getName(), sysDict.getName(),showNameList));
            }
        }
        return new ReturnResult(selectVoList);
    }

}